package com.qf.fmall.shopcart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmall.index.entity.Product;
import com.qf.fmall.index.entity.ProductImg;
import com.qf.fmall.index.mapper.ProductImgMapper;
import com.qf.fmall.index.mapper.ProductMapper;
import com.qf.fmall.product.entity.ProductSku;
import com.qf.fmall.product.mapper.ProductSkuMapper;
import com.qf.fmall.shopcart.entity.ShoppingCart;
import com.qf.fmall.shopcart.mapper.ShoppingCartMapper;
import com.qf.fmall.shopcart.service.IShoppingCartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author weijy
 * @since 2024-01-17
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements IShoppingCartService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private ProductImgMapper productImgMapper;


    @Override
    public List<ShoppingCart> getListByUserId(Integer userId) {

        List<ShoppingCart> cartList = list(new QueryWrapper<ShoppingCart>().eq("user_id", userId));

        addExtraInfo(cartList);

        return cartList;
    }

    private void addExtraInfo(List<ShoppingCart> cartList) {
        /**
         *  "productName": "咪咪小虾条",
         * 	"productImg": "mmxt_1.png",
         * 	"skuName": "咪咪虾条 单包 50g",
         * 	"originalPrice": 2,
         * 	"sellPrice": 1,
         * 	"stock": 254
         */

        for (ShoppingCart cart : cartList) {

            // 处理商品名字
            Integer productId = cart.getProductId();
            Product product = productMapper.selectById(productId);
            cart.setProductName(product.getProductName());

            // 处理商品图片
            ProductImg productImg = productImgMapper
                    .selectOne(new QueryWrapper<ProductImg>()
                            .eq("product_id", productId).eq("is_main", 1));
            cart.setProductImg(productImg.getUrl());

            // 处理商品套餐信息
            String skuId = cart.getSkuId();
            ProductSku productSku = productSkuMapper.selectById(skuId);
            cart.setSkuName(productSku.getSkuName());
            cart.setOriginalPrice(String.valueOf(productSku.getOriginalPrice()));
            cart.setSellPrice(String.valueOf(productSku.getSellPrice()));
            cart.setStock(String.valueOf(productSku.getStock()));
        }
    }

    @Override
    public List<ShoppingCart> getListByCids(List<String> cids) {

        List<ShoppingCart> cartList = list(new QueryWrapper<ShoppingCart>().in("cart_id", cids));

        addExtraInfo(cartList);

        return cartList;
    }
}
